﻿using Nop.Core;
using Nop.Core.Domain;
using Nop.Core.Domain.Customers;
using Nop.Core.Domain.Localization;
using Nop.Core.Domain.Media;
using Nop.Services.Authentication;
using Nop.Services.Authentication.External;
using Nop.Services.Common;
using Nop.Services.Customers;
using Nop.Services.Directory;
using Nop.Services.Events;
using Nop.Services.Helpers;
using Nop.Services.Localization;
using Nop.Services.Logging;
using Nop.Services.Media;
using Nop.Services.Security;
using Nop.Services.Stores;
using Nop.Web.Factories;
using Nop.Web.Framework;
using Nop.Web.Framework.Kendoui;
using Nop.Web.Framework.Security;
using Nop.Web.Framework.Security.Captcha;
using Nop.Web.Framework.Security.Honeypot;
using Nop.Web.Models.Customer;
using Senparc.Weixin;
using Senparc.Weixin.WxOpen.AdvancedAPIs.Sns;
using Senparc.Weixin.WxOpen.Containers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;

namespace Nop.Web.Controllers
{
	public partial class CustomerController : BasePublicController
	{
		#region Fields

		private readonly IPermissionAntService _permissionAntService;
		private readonly ICustomerModelFactory _customerModelFactory;
		private readonly IAuthenticationService _authenticationService;
		private readonly DateTimeSettings _dateTimeSettings;
		private readonly ILocalizationService _localizationService;
		private readonly IWorkContext _workContext;
		private readonly IStoreContext _storeContext;
		private readonly IOrganizationService _organizationService;
		private readonly ICustomerService _customerService;
		private readonly IGenericAttributeService _genericAttributeService;
		private readonly ICustomerRegistrationService _customerRegistrationService;
		private readonly CustomerSettings _customerSettings;
		private readonly ICountryService _countryService;
		private readonly IPictureService _pictureService;
		private readonly IWebHelper _webHelper;
		private readonly ICustomerActivityService _customerActivityService;
		private readonly IStoreService _storeService;
		private readonly IEventPublisher _eventPublisher;
		private readonly MediaSettings _mediaSettings;
		private readonly LocalizationSettings _localizationSettings;
		private readonly CaptchaSettings _captchaSettings;
		private readonly StoreInformationSettings _storeInformationSettings;
		private readonly IDepartmentService _departmentService;
		private readonly IPersonService _personService;

		#endregion

		#region Ctor

		public CustomerController(IPermissionAntService permissionAntService,
			ICustomerModelFactory customerModelFactory,
			IAuthenticationService authenticationService,
			DateTimeSettings dateTimeSettings,
			ILocalizationService localizationService,
			IWorkContext workContext,
			IStoreContext storeContext,
			IOrganizationService organizationService,
			ICustomerService customerService,
			IGenericAttributeService genericAttributeService,
			ICustomerRegistrationService customerRegistrationService,
			CustomerSettings customerSettings,
			ICountryService countryService,
			IPictureService pictureService,
			IWebHelper webHelper,
			ICustomerActivityService customerActivityService,
			IStoreService storeService,
			IEventPublisher eventPublisher,
			MediaSettings mediaSettings,
			LocalizationSettings localizationSettings,
			CaptchaSettings captchaSettings,
			StoreInformationSettings storeInformationSettings,
			IDepartmentService departmentService,
			IPersonService personService)
		{
			this._permissionAntService = permissionAntService;
			this._customerModelFactory = customerModelFactory;
			this._authenticationService = authenticationService;
			this._dateTimeSettings = dateTimeSettings;
			this._localizationService = localizationService;
			this._workContext = workContext;
			this._storeContext = storeContext;
			this._organizationService = organizationService;
			this._customerService = customerService;
			this._genericAttributeService = genericAttributeService;
			this._customerRegistrationService = customerRegistrationService;
			this._customerSettings = customerSettings;
			this._countryService = countryService;
			this._pictureService = pictureService;
			this._webHelper = webHelper;
			this._customerActivityService = customerActivityService;
			this._storeService = storeService;
			this._eventPublisher = eventPublisher;
			this._mediaSettings = mediaSettings;
			this._localizationSettings = localizationSettings;
			this._captchaSettings = captchaSettings;
			this._storeInformationSettings = storeInformationSettings;
			this._departmentService = departmentService;
			this._personService = personService;
		}

		#endregion

		#region Utilities

		[NonAction]
		private bool SecondAdminAccountExists(Customer customer)
		{
			var customers = _customerService.GetAllCustomers(customerRoleIds: new[] { _customerService.GetCustomerRoleBySystemName(SystemCustomerRoleNames.Administrators).Id });

			return customers.Any(c => c.Active && c.Id != customer.Id);
		}

		[NonAction]
		protected virtual CustomerRoleModel PrepareCustomerRoleModelForList(CustomerRole p)
		{
			return new CustomerRoleModel
			{
				key = p.Id,
				SystemName = p.SystemName,
				Name = p.Name,
				IsSystemRole = p.IsSystemRole,
				Active = p.Active,
			};
		}

		[NonAction]
		protected virtual string GetCustomerRolesNames(IList<CustomerRole> customerRoles, string separator = ",")
		{
			var sb = new StringBuilder();
			for (int i = 0; i < customerRoles.Count; i++)
			{
				sb.Append(customerRoles[i].Name);
				if (i != customerRoles.Count - 1)
				{
					sb.Append(separator);
					sb.Append(" ");
				}
			}
			return sb.ToString();
		}

		[NonAction]
		protected virtual CustomerModel PrepareCustomerModelForList(Customer p)
		{
			return new CustomerModel
			{
				key = p.Id,
				Username = p.Username,
				TrueName = p.TrueName,
				TelPhone = p.TelPhone,
				CustomerRoleNames = GetCustomerRolesNames(p.CustomerRoles.ToList()),
				DepartmentId = p.DepartmentId,
				DepartmentName = _departmentService.GetNameById(p.DepartmentId),
				SelectedCustomerRoleIds = p.CustomerRoles.Select(x => x.Id).ToList(),
				Active = p.Active,
				CreatedOn = p.CreatedOnUtc,
			};
		}

		[NonAction]
		protected virtual PersonModel PreparePersonModelForList(Person p)
		{
			return new PersonModel
			{
				key = p.Id,
				Name = p.Name,
				DepartmentId = p.DepartmentId,
				DepartmentName = _departmentService.GetNameById(p.DepartmentId),
				BMNSJG = p.BMNSJG,
				GWMC = p.GWMC,
				GWXZ = p.GWXZ,
				GWXZName = p.GWXZ > 0 ? Enum.GetName(typeof(GWXZEnum), p.GWXZ) : "",
				TelPhone = p.TelPhone,
				GenderId = p.GenderId,
				Gender = p.GenderId > 0 ? Enum.GetName(typeof(GenderEnum), p.GenderId) : "",
				SFZH = p.SFZH,
				BirthOn = p.BirthOn,
				WorkOn = p.WorkOn,
				NationId = p.NationId,
				Nation = p.NationId > 0 ? Enum.GetName(typeof(NationEnum), p.GenderId) : "",
				Birthplace = p.Birthplace,
				PoliticsStatus = p.PoliticsStatus,
				PoliticsStatusName = p.NationId > 0 ? Enum.GetName(typeof(PoliticsStatusEnum), p.GenderId) : "",
				JoinOn = p.JoinOn,
				Status = p.Status,
				StatusName = p.Status > 0 ? Enum.GetName(typeof(WorkStatusEnum), p.Status) : "",
				Nature = p.Nature,
				NatureName = p.Status > 0 ? Enum.GetName(typeof(NatureEnum), p.Nature) : "",
				Education = p.Education,
				EducationName = p.Education > 0 ? Enum.GetName(typeof(EducationEnum), p.Education) : "",
				School = p.School,
				Degree = p.Degree,
				ZC = p.ZC,
				ZCLevel = p.ZCLevel,
				ZCLevelName = p.ZCLevel > 0 ? Enum.GetName(typeof(ZCLevelEnum), p.ZCLevel) : "",
				JN = p.JN,
				JNLevel = p.JNLevel,
				JNLevelName = p.JNLevel > 0 ? Enum.GetName(typeof(JNLevelEnum), p.JNLevel) : "",
			};
		}

		[NonAction]
		protected virtual PersonExportModel PreparePersonExportModelForList(Person p)
		{
			return new PersonExportModel
			{
				key = p.Id,
				Name = p.Name,
				DepartmentName = _departmentService.GetNameById(p.DepartmentId),
				BMNSJG = p.BMNSJG,
				GWMC = p.GWMC,
				GWXZName = p.GWXZ > 0 ? Enum.GetName(typeof(GWXZEnum), p.GWXZ) : "",
				TelPhone = p.TelPhone,
				Gender = p.GenderId > 0 ? Enum.GetName(typeof(GenderEnum), p.GenderId) : "",
				SFZH = p.SFZH,
				BirthOn = p.BirthOn,
				WorkOn = p.WorkOn,
				Nation = p.NationId > 0 ? Enum.GetName(typeof(NationEnum), p.GenderId) : "",
				Birthplace = p.Birthplace,
				PoliticsStatusName = p.NationId > 0 ? Enum.GetName(typeof(PoliticsStatusEnum), p.GenderId) : "",
				JoinOn = p.JoinOn,
				StatusName = p.Status > 0 ? Enum.GetName(typeof(WorkStatusEnum), p.Status) : "",
				NatureName = p.Status > 0 ? Enum.GetName(typeof(NatureEnum), p.Nature) : "",
				EducationName = p.Education > 0 ? Enum.GetName(typeof(EducationEnum), p.Education) : "",
				School = p.School,
				Degree = p.Degree,
				ZC = p.ZC,
				ZCLevelName = p.ZCLevel > 0 ? Enum.GetName(typeof(ZCLevelEnum), p.ZCLevel) : "",
				JN = p.JN,
				JNLevelName = p.JNLevel > 0 ? Enum.GetName(typeof(JNLevelEnum), p.JNLevel) : "",
			};
		}
		#endregion

		#region Login / logout

		[NopHttpsRequirement(SslRequirement.Yes)]
		//available even when navigation is not allowed
		[PublicStoreAllowNavigation(true)]
		public virtual ActionResult Login(bool? checkoutAsGuest)
		{
			var model = _customerModelFactory.PrepareLoginModel(checkoutAsGuest);
			return View(model);
		}

		//available even when navigation is not allowed
		[PublicStoreAllowNavigation(true)]
		public virtual ActionResult Logout()
		{
			//external authentication
			ExternalAuthorizerHelper.RemoveParameters();

			//activity log
			_customerActivityService.InsertActivity("PublicStore.Logout", _localizationService.GetResource("ActivityLog.PublicStore.Logout"));

			//standard logout 
			_authenticationService.SignOut();

			//raise logged out event       
			_eventPublisher.Publish(new CustomerLoggedOutEvent(_workContext.CurrentCustomer));

			return RedirectToRoute("Login");
		}

		/// <summary>
		/// 获取用户密码后缀
		/// 密码+后缀
		/// </summary>
		/// <param name="username"></param>
		/// <returns></returns>
		[HttpPost]
		public JsonResult GetPasswordSalt(string username)
		{
			var customer = _customerService.GetCustomerByUsername(username);
			if (null == customer)
				return Json(new { result = false, msg = "账户不存在" });
			var password = _customerService.GetCurrentPassword(customer.Id);
			if (null == password)
				return Json(new { result = false, msg = "密码错误" });
			return Json(new { result = true, passwordsalt = password.PasswordSalt });
		}

		[HttpPost]
		public JsonResult DoLogin(string userinp, string password, string code = null)
		{
			if (!string.IsNullOrEmpty(code) && code != Session["CaptchaImageText"] as string)
				return Json(new { code = "3", msg = "验证码错误" });
			var loginResult = _customerRegistrationService.ValidateCustomer4SHAl(userinp, password);
			switch (loginResult)
			{
				case CustomerLoginResults.Successful:
					var customer = _customerService.GetCustomerByUsername(userinp);

					//sign in new customer
					_authenticationService.SignIn(customer, true);

					//raise event       
					_eventPublisher.Publish(new CustomerLoggedinEvent(customer));

					//activity log
					_customerActivityService.InsertActivity(customer, "PublicStore.Login", _localizationService.GetResource("ActivityLog.PublicStore.Login"));
					string url = Request.ApplicationPath;
					if (url == "/")
					{
						url = "/Admin";
					}
					else
					{
						url += "/Admin";
					}
					return Json(new { code = "0", msg = new MsgModel { setTime = 3, msg = string.Format("{0}欢迎登陆", customer.TrueName ?? customer.Username), URL = url, jump = true } });
				case CustomerLoginResults.CustomerNotExist:
					return Json(new { code = "1", msg = "账户不存在" });
				case CustomerLoginResults.WrongPassword:
					return Json(new { code = "2", msg = "密码错误" });
				case CustomerLoginResults.NotActive:
					return Json(new { code = "1", msg = "账户未激活" });
				case CustomerLoginResults.Deleted:
					return Json(new { code = "1", msg = "账户已删除" });
				case CustomerLoginResults.NotRegistered:
					return Json(new { code = "1", msg = "账户未注册" });
				case CustomerLoginResults.LockedOut:
					return Json(new { code = "1", msg = "账户已锁死" });
				default:
					return Json(new { code = "1", msg = "账户不存在" });
			}
		}

		#endregion

		#region Register

		[NopHttpsRequirement(SslRequirement.Yes)]
		//available even when navigation is not allowed
		[PublicStoreAllowNavigation(true)]
		public virtual ActionResult Register()
		{
			//check whether registration is allowed
			if (_customerSettings.UserRegistrationType == UserRegistrationType.Disabled)
				return RedirectToRoute("RegisterResult", new { resultId = (int)UserRegistrationType.Disabled });

			var model = new RegisterModel();
			model = _customerModelFactory.PrepareRegisterModel(model, false, setDefaultValues: true);

			return View(model);
		}

		[HttpPost]
		[HoneypotValidator]
		[PublicAntiForgery]
		[ValidateInput(false)]
		//available even when navigation is not allowed
		[PublicStoreAllowNavigation(true)]
		public virtual ActionResult Register(RegisterModel model, string returnUrl, FormCollection form)
		{
			//check whether registration is allowed
			if (_customerSettings.UserRegistrationType == UserRegistrationType.Disabled)
				return RedirectToRoute("RegisterResult", new { resultId = (int)UserRegistrationType.Disabled });

			if (_workContext.CurrentCustomer.IsRegistered())
			{
				//Already registered customer. 
				_authenticationService.SignOut();

				//raise logged out event       
				_eventPublisher.Publish(new CustomerLoggedOutEvent(_workContext.CurrentCustomer));

				//Save a new record
				_workContext.CurrentCustomer = _customerService.InsertGuestCustomer();
			}
			var customer = _workContext.CurrentCustomer;
			customer.RegisteredInStoreId = _storeContext.CurrentStore.Id;

			//validate CAPTCHA
			//if (_captchaSettings.Enabled && _captchaSettings.ShowOnRegistrationPage && !captchaValid)
			//{
			//    ModelState.AddModelError("", _captchaSettings.GetWrongCaptchaMessage(_localizationService));
			//}
			if (string.IsNullOrEmpty(model.Captcha) || model.Captcha != Session["CaptchaImageText"] as string)
				ModelState.AddModelError("", "验证码错误");

			if (ModelState.IsValid)
			{
				if (model.Username != null)
				{
					model.Username = model.Username.Trim();
				}

				bool isApproved = _customerSettings.UserRegistrationType == UserRegistrationType.Standard;
				var registrationRequest = new CustomerRegistrationRequest(customer,
					model.Username,
					model.TrueName,
					model.Password,
					_customerSettings.DefaultPasswordFormat,
					_storeContext.CurrentStore.Id,
					isApproved);
				var registrationResult = _customerRegistrationService.RegisterCustomer(registrationRequest);
				if (registrationResult.Success)
				{
					//form fields
					if (_customerSettings.GenderEnabled)
						_genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.Gender, model.Gender);
					if (_customerSettings.DateOfBirthEnabled)
					{
						DateTime? dateOfBirth = model.ParseDateOfBirth();
						_genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.DateOfBirth, dateOfBirth);
					}

					//login customer now
					if (isApproved)
						_authenticationService.SignIn(customer, true);


					////notifications
					//if (_customerSettings.NotifyNewCustomerRegistration)
					//    _workflowMessageService.SendCustomerRegisteredNotificationMessage(customer,
					//        _localizationSettings.DefaultAdminLanguageId);

					//raise event       
					_eventPublisher.Publish(new CustomerRegisteredEvent(customer));

					switch (_customerSettings.UserRegistrationType)
					{
						//case UserRegistrationType.EmailValidation:
						//    {
						//        //email validation message
						//        _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.AccountActivationToken, Guid.NewGuid().ToString());
						//        //_workflowMessageService.SendCustomerEmailValidationMessage(customer, _workContext.WorkingLanguage.Id);

						//        //result
						//        return RedirectToRoute("RegisterResult",
						//            new { resultId = (int)UserRegistrationType.EmailValidation });
						//    }
						case UserRegistrationType.AdminApproval:
							{
								return RedirectToRoute("RegisterResult",
									new { resultId = (int)UserRegistrationType.AdminApproval });
							}
						case UserRegistrationType.Standard:
							{
								//send customer welcome message
								//_workflowMessageService.SendCustomerWelcomeMessage(customer, _workContext.WorkingLanguage.Id);

								var redirectUrl = Url.RouteUrl("RegisterResult", new { resultId = (int)UserRegistrationType.Standard });
								if (!String.IsNullOrEmpty(returnUrl) && Url.IsLocalUrl(returnUrl))
									redirectUrl = _webHelper.ModifyQueryString(redirectUrl, "returnurl=" + HttpUtility.UrlEncode(returnUrl), null);
								return Redirect(redirectUrl);
							}
						default:
							{
								return RedirectToRoute("HomePage");
							}
					}
				}

				//errors
				foreach (var error in registrationResult.Errors)
					ModelState.AddModelError("", error);
			}

			//If we got this far, something failed, redisplay form
			model = _customerModelFactory.PrepareRegisterModel(model, true);
			return View(model);
		}
		#endregion

		#region Change password

		/// <summary>
		/// 修改用户密码
		/// </summary>
		/// <param name="username">用户名</param>
		/// <param name="oldpwd">原密码</param>
		/// <param name="newpwd">新密码</param>
		/// <returns></returns>
		[HttpPost]
		[UserValidator]
		public JsonResult ChangePassword(Customer customer, string oldpwd, string newpwd)
		{
			if (customer != null && customer.Active && !customer.Deleted)
			{
				var response = _customerRegistrationService.ChangePassword(new ChangePasswordRequest(customer.Username, true, _customerSettings.DefaultPasswordFormat, newpwd, oldpwd));
				if (response.Success)
				{
					//修改密码后作废身份令牌
					if (!string.IsNullOrEmpty(customer.Token))
					{
						customer.Token = null;
						customer.TokenIndate = null;
						_customerService.UpdateCustomer(customer);
					}
					return Json(new { result = true, msg = "密码修改成功" });
				}
				else
				{
					return Json(new { result = false, msg = response.Errors.FirstOrDefault() });
				}
			}
			return Json(new { result = false, msg = "用户无效" });
		}

		/// <summary>
		/// 修改用户密码
		/// </summary>
		/// <param name="model"></param>
		/// <param name="guid"></param>
		/// <returns></returns>
		[HttpPost]
		public JsonResult SaveChangePassword(ChangePasswordModel model, string guid)
		{
			if (string.IsNullOrEmpty(model.NewPassword) || model.NewPassword.Length > 12 || model.NewPassword.Length < 6)
				return Json(new { result = false, msg = "请重新设置新密码" });
			try
			{
				var customer = _customerService.GetCustomerByToken(guid);
				if (null != customer)
				{
					var changePasswordRequest = new ChangePasswordRequest(customer.Username, true, _customerSettings.DefaultPasswordFormat, model.NewPassword, model.OldPassword);
					var changePasswordResult = _customerRegistrationService.ChangePassword(changePasswordRequest);
					if (changePasswordResult.Success)
					{
						//修改密码后作废身份令牌
						if (!string.IsNullOrEmpty(customer.Token))
						{
							customer.Token = null;
							customer.TokenIndate = null;
							_customerService.UpdateCustomer(customer);
						}
						//activity log
						_customerActivityService.InsertActivity("EditCustomer", "修改密码 Id={0}", customer.Id);
						return Json(new { result = true });
					}
					//errors
					foreach (var error in changePasswordResult.Errors)
						return Json(new { result = false, msg = error });
				}
				else
					return Json(new { result = false, msg = "用户无效" });
			}
			catch (Exception ex)
			{
				return Json(new { result = false, msg = ex.Message });
			}
			return Json(new { result = false, msg = "失败" });
		}

		/// <summary>
		/// 重置密码
		/// </summary>
		/// <param name="key"></param>
		/// <param name="guid"></param>
		/// <returns></returns>
		[HttpPost]
		public JsonResult ResetPassword(int key, string guid)
		{
			var currentCustomer = _customerService.GetCustomerByToken(guid);
			if (null != currentCustomer)
			{
				var customer = _customerService.GetCustomerById(key);
				if (null != customer)
				{
					if (customer.IsAdmin() && !currentCustomer.IsAdmin())
						return Json(new { result = false, msg = "无权修改管理员密码" });
					var changePassRequest = new ChangePasswordRequest(customer.Username, false, _customerSettings.DefaultPasswordFormat, "123456");
					var changePassResult = _customerRegistrationService.ChangePassword(changePassRequest);
					if (!changePassResult.Success)
					{
						//修改密码后作废身份令牌
						if (!string.IsNullOrEmpty(customer.Token))
						{
							customer.Token = null;
							customer.TokenIndate = null;
							_customerService.UpdateCustomer(customer);
						}
						return Json(new { result = false, msg = "密码修改失败" });
					}

					//activity log
					_customerActivityService.InsertActivity(currentCustomer, "ResetCustomerPassword", "重置用户{0}密码 Id={1}", customer.Username, customer.Id);
					return Json(new { result = true });
				}
			}
			return Json(new { result = false, msg = "用户无效" });
		}

		#endregion

		#region Customer

		/// <summary>
		/// 登录
		/// </summary>
		/// <param name="userName"></param>
		/// <param name="password"></param>
		/// <param name="type"></param>
		/// <returns></returns>
		[HttpPost]
		public JsonResult Login(string userName, string password, string type = "account")
		{
			string msg = string.Empty;
			var loginResult = _customerRegistrationService.ValidateCustomer4SHAl(userName, password);
			switch (loginResult)
			{
				case CustomerLoginResults.Successful:
					// 刷新令牌并获取用户信息
					var customer = _customerService.GetCustomerAfterGenerateToken(userName);
					if (null == customer)
						return Json(new
						{
							status = "error",
							type,
							guid = "",
							currentAuthority = "guest"
						});
					//raise event       
					_eventPublisher.Publish(new CustomerLoggedinEvent(customer));
					//activity log
					_customerActivityService.InsertActivity(customer, "PublicStore.Login", "登录");

					return Json(new
					{
						status = "ok",
						type,
						guid = customer.Token,
						currentAuthority = customer.CustomerRoles.Select(x => x.SystemName).ToList()
					});
				case CustomerLoginResults.CustomerNotExist:
					msg = "用户不存在";
					break;
				case CustomerLoginResults.Deleted:
					msg = "用户已删除";
					break;
				case CustomerLoginResults.NotActive:
					msg = "用户未激活";
					break;
				case CustomerLoginResults.NotRegistered:
					msg = "用户未注册";
					break;
				case CustomerLoginResults.LockedOut:
					msg = "用户已冻结";
					break;
				case CustomerLoginResults.WrongPassword:
				default:
					msg = "密码错误";
					break;
			}
			return Json(new
			{
				status = "error",
				type,
				guid = "",
				currentAuthority = "guest"
			});
		}

		/// <summary>
		/// 当前用户信息
		/// </summary>
		/// <param name="guid"></param>
		/// <returns></returns>
		public JsonResult CurrentUser(string guid)
		{
			var model = new CurrentUserModel();
			var customer = _customerService.GetCustomerByToken(guid);
			if (null != customer)
			{
				model.userid = customer.Id;
				model.name = customer.TrueName;
				model.tel = customer.TelPhone;
				int avatarPictureId = customer.GetAttribute<int>(SystemCustomerAttributeNames.AvatarPictureId);
				if (avatarPictureId > 0)
					model.avatar = _pictureService.GetPictureUrl(avatarPictureId, 200);
				else
					model.avatar = "https://gw.alipayobjects.com/zos/rmsportal/BiazfanxmamNRoxxVxka.png";
				model.unreadCount = 0;

				model.key = customer.Id;
				model.Username = customer.Username;
				model.TrueName = customer.TrueName;
				model.TelPhone = customer.TelPhone;
				model.DepartmentName = _departmentService.GetNameById(customer.DepartmentId);
				return Json(new { result = true, model }, JsonRequestBehavior.AllowGet);
			}
			else
				return Json(new { result = false, msg = "请重新登录" }, JsonRequestBehavior.AllowGet);
		}

		/// <summary>
		/// 用户列表
		/// </summary>
		/// <param name="model"></param>
		/// <param name="guid"></param>
		/// <param name="currentPage"></param>
		/// <param name="pageSize"></param>
		/// <param name="sorter"></param>
		/// <returns></returns>
		[HttpPost]
		public JsonResult CustomerList(CustomerListModel model, string guid = "", int currentPage = 1, int pageSize = 10, string sorter = "")
		{
			if (!_permissionAntService.Authorize(guid, (int)PermissionAntEnum.customerlist))
				return Json(new { result = false, msg = "无权访问" });

			if (model.SelectedCustomerRoleIds == null || (model.SelectedCustomerRoleIds.Count == 0))
				model.SelectedCustomerRoleIds.Add(_customerService.GetCustomerRoleBySystemName(SystemCustomerRoleNames.Registered).Id);

			var customers = _customerService.GetAllCustomers(
				departId: model.DepartmentId,
				username: model.Username,
				firstName: model.TrueName,
				customerRoleIds: model.SelectedCustomerRoleIds.ToArray(),
				pageIndex: currentPage - 1,
				pageSize: pageSize
				);
			var gridModel = new DataSourceResultAnt
			{
				list = customers.Select(PrepareCustomerModelForList),
				pagination = new PaginationModel
				{
					total = customers.TotalCount,
					pageSize = pageSize,
					current = currentPage
				}
			};
			return Json(new { result = true, gridModel });
		}

		/// <summary>
		/// 列表筛选条件
		/// </summary>
		/// <returns></returns>
		public JsonResult CustomerListFilter()
		{
			var model = new CustomerListModel();
			var roles = _customerService.GetAllCustomerRoles().Where(m => m.SystemName != SystemCustomerRoleNames.Guests);
			foreach (var role in roles)
			{
				model.CustomerRoles.Add(new ItemModel { key = role.Id.ToString(), value = role.Name });
			}
			model.SelectedCustomerRoleIds.Add(_customerService.GetCustomerRoleBySystemName(SystemCustomerRoleNames.Registered).Id);
			model.Departments.Add(new ItemModel { key = "0", value = "全部" });
			var departments = _departmentService.GetAllDepartments().Where(m => m.Active && !m.Deleted).ToList();
			foreach (var d in departments)
			{
				model.Departments.Add(new ItemModel { key = d.Id.ToString(), value = d.Name });
			}
			return Json(model, JsonRequestBehavior.AllowGet);
		}
		/// <summary>
		/// 保存用户信息
		/// </summary>
		/// <param name="model"></param>
		/// <param name="guid"></param>
		/// <returns></returns>
		[HttpPost]
		public JsonResult SaveCustomer(CustomerModel model, string guid)
		{
			if (!_permissionAntService.Authorize(guid, (int)PermissionAntEnum.customerlist))
				return Json(new { result = false, msg = "无权访问" });
			try
			{
				//validate customer roles
				var allCustomerRoles = _customerService.GetAllCustomerRoles(showAll: true);
				var registerId = allCustomerRoles.FirstOrDefault(m => m.SystemName == SystemCustomerRoleNames.Registered).Id;
				if (!model.SelectedCustomerRoleIds.Contains(registerId))
					return Json(new { result = false, msg = "角色必须包含注册" });
				var customer = _customerService.GetCustomerByToken(guid);
				if (null != customer)
				{
					if (model.key == 0)
					{
						var cust2 = _customerService.GetCustomerByUsername(model.Username);
						if (cust2 != null)
							return Json(new { result = false, msg = "用户名已经注册" });
						var newCustomer = new Customer
						{
							CustomerGuid = Guid.NewGuid(),
							Username = model.Username,
							TrueName = model.TrueName,
							TelPhone = model.TelPhone,
							DepartmentId = model.DepartmentId,
							Active = model.Active,
							CreatedOnUtc = DateTime.Now,
							LastActivityDateUtc = DateTime.Now
						};
						_customerService.InsertCustomer(newCustomer);

						#region 密码
						string password = string.IsNullOrEmpty(model.Password) ? "123456" : model.Password;
						var changePassRequest = new ChangePasswordRequest(newCustomer.Username, false, _customerSettings.DefaultPasswordFormat, password);
						var changePassResult = _customerRegistrationService.ChangePassword(changePassRequest);
						if (!changePassResult.Success)
						{
							return Json(new { result = false, msg = "密码修改失败" });
						}
						#endregion
						#region 角色
						var newCustomerRoles = new List<CustomerRole>();
						foreach (var customerRole in allCustomerRoles)
							if (model.SelectedCustomerRoleIds.Contains(customerRole.Id))
								newCustomerRoles.Add(customerRole);
						//customer roles
						foreach (var customerRole in newCustomerRoles)
						{
							//ensure that the current customer cannot add to "Administrators" system role if he's not an admin himself
							if (customerRole.SystemName == SystemCustomerRoleNames.Administrators &&
								!_workContext.CurrentCustomer.IsAdmin())
								continue;

							newCustomer.CustomerRoles.Add(customerRole);
						}
						#endregion
						_customerService.UpdateCustomer(newCustomer);

						//activity log
						_customerActivityService.InsertActivity("AddNewCustomer", "新增用户 Id={0}", newCustomer.Id);

					}
					else
					{
						var newCustomer = _customerService.GetCustomerById(model.key);
						if (null != newCustomer)
						{
							if (!newCustomer.IsAdmin() || model.Active || SecondAdminAccountExists(customer))
								newCustomer.Active = model.Active;
							newCustomer.TrueName = model.TrueName;
							newCustomer.TelPhone = model.TelPhone;
							newCustomer.DepartmentId = model.DepartmentId;
							// 编辑用户后作废身份牌
							newCustomer.Token = null;
							newCustomer.TokenIndate = null;
							if (!string.IsNullOrWhiteSpace(model.Username) && model.Username != newCustomer.Username)
							{
								_customerRegistrationService.SetUsername(newCustomer, model.Username);
							}
							#region 角色
							//customer roles
							foreach (var customerRole in allCustomerRoles)
							{
								//ensure that the current customer cannot add/remove to/from "Administrators" system role
								//if he's not an admin himself
								if (customerRole.SystemName == SystemCustomerRoleNames.Administrators &&
									!_workContext.CurrentCustomer.IsAdmin())
									continue;

								if (model.SelectedCustomerRoleIds.Contains(customerRole.Id))
								{
									//new role
									if (newCustomer.CustomerRoles.Count(cr => cr.Id == customerRole.Id) == 0)
										newCustomer.CustomerRoles.Add(customerRole);
								}
								else
								{
									//prevent attempts to delete the administrator role from the user, if the user is the last active administrator
									if (newCustomer.SystemName == SystemCustomerRoleNames.Administrators && !SecondAdminAccountExists(newCustomer))
									{
										ErrorNotification(_localizationService.GetResource("Admin.Customers.Customers.AdminAccountShouldExists.DeleteRole"));
										continue;
									}

									//remove role
									if (newCustomer.CustomerRoles.Count(cr => cr.Id == customerRole.Id) > 0)
										newCustomer.CustomerRoles.Remove(customerRole);
								}
							}
							#endregion
							_customerService.UpdateCustomer(newCustomer);
							//activity log
							_customerActivityService.InsertActivity("EditCustomer", "修改用户 Id={0}", newCustomer.Id);

						}
					}
					return Json(new { result = true });
				}
				else
					return Json(new { result = false, msg = "用户无效" });
			}
			catch (Exception ex)
			{
				return Json(new { result = false, msg = ex.Message });
			}
		}

		/// <summary>
		/// 修改自己的基本信息
		/// </summary>
		/// <param name="model"></param>
		/// <param name="guid"></param>
		/// <returns></returns>
		[HttpPost]
		public JsonResult SaveCustomerBasic(CustomerModel model, string guid)
		{
			try
			{
				var customer = _customerService.GetCustomerByToken(guid);
				if (null != customer)
				{
					if (customer.Id != model.key)
						return Json(new { result = false, msg = "无权修改" });

					customer.TrueName = model.TrueName;
					customer.TelPhone = model.TelPhone;
					//if (!string.IsNullOrWhiteSpace(model.Username) && model.Username != customer.Username)
					//{
					//    _customerRegistrationService.SetUsername(customer, model.Username);
					//}
					_customerService.UpdateCustomer(customer);
					//activity log
					_customerActivityService.InsertActivity("EditCustomer", "修改用户 Id={0}", customer.Id);
					return Json(new { result = true });
				}
				else
					return Json(new { result = false, msg = "用户无效" });
			}
			catch (Exception ex)
			{
				return Json(new { result = false, msg = ex.Message });
			}
		}

		/// <summary>
		/// 删除用户信息
		/// </summary>
		/// <param name="key"></param>
		/// <returns></returns>
		[HttpPost]
		public JsonResult DeleteCustomer(int[] key, string guid)
		{
			if (!_permissionAntService.Authorize(guid, (int)PermissionAntEnum.customerlist))
				return Json(new { result = false, msg = "无权访问" });
			try
			{
				var customer = _customerService.GetCustomerByToken(guid);
				if (null != customer)
				{
					foreach (var id in key)
					{
						var newcustomer = _customerService.GetCustomerById(id);
						if (null != newcustomer)
						{
							if (newcustomer.IsAdmin() && !SecondAdminAccountExists(newcustomer))
							{
								return Json(new { result = false, msg = "不能删除仅有的管理员" });
							}
							if (newcustomer.IsAdmin() && !customer.IsAdmin())
							{
								return Json(new { result = false, msg = "只有管理员能删除" });
							}
							newcustomer.Deleted = true;
							_customerService.UpdateCustomer(newcustomer);

							//activity log
							_customerActivityService.InsertActivity("DeleteCustomer", "删除用户 Id={0}", newcustomer.Id);

						}
					}
				}
			}
			catch (Exception ex)
			{
				return Json(new { result = false, msg = ex.Message });
			}
			return Json(new { result = true });
		}

		/// <summary>
		/// 获取上级及平级领导
		/// </summary>
		/// <param name="guid"></param>
		/// <returns></returns>
		[HttpPost]
		public JsonResult GetLeaders(string guid)
		{
			var model = new List<ItemModel>();
			var customer = _customerService.GetCustomerByToken(guid);
			if (customer != null)
			{
				int topDisplayOrder = customer.CustomerRoles.OrderByDescending(m => m.DisplayOrder).FirstOrDefault().DisplayOrder;//当前用户的最大角色
				var customers = _customerService.GetLeaders(customerRoleIds: _customerService.GetCommonCustomerRoles().Where(m => m.DisplayOrder > 0 && m.DisplayOrder >= topDisplayOrder).Select(x => x.Id).ToArray(), customerId: customer.Id);
				foreach (var c in customers)
				{
					model.Add(new ItemModel
					{
						key = c.Id.ToString(),
						value = c.TrueName ?? c.Username
					});
				}
			}
			return Json(new { result = true, model });
		}

		/// <summary>
		/// 登录、绑定openid
		/// </summary>
		/// <param name="username"></param>
		/// <param name="password"></param>
		/// <param name="openId"></param>
		/// <returns></returns>
		[HttpPost]
		public JsonResult WXLogin(string username, string password, string openId = "")
		{
			string msg = string.Empty;
			var loginResult = _customerRegistrationService.ValidateCustomer(username, password);
			switch (loginResult)
			{
				case CustomerLoginResults.Successful:
					{
						var customer = _customerService.GetCustomerAfterGenerateToken(username);

						//raise event       
						_eventPublisher.Publish(new CustomerLoggedinEvent(customer));

						//activity log
						_customerActivityService.InsertActivity(customer, "PublicStore.Login", "登录");
						var model = new UserModel();
						model.Id = customer.Id;
						model.DepartmentName = customer.DepartmentName;
						model.TeamName = customer.TeamName;
						model.TrueName = customer.TrueName;
						model.UserName = customer.Username;
						model.Token = customer.Token;

						if (customer.IsAdmin())
						{
							model.Level = "Admin";
							var role = _customerService.GetCustomerRoleBySystemName(SystemCustomerRoleNames.Administrators);
							if (null != role)
								model.LevelName = role.Name;
						}
						else if (customer.IsRepairman())
						{
							model.Level = "Member";
							var role = _customerService.GetCustomerRoleBySystemName(SystemCustomerRoleNames.Repairman);
							if (null != role)
								model.LevelName = role.Name;
						}
						else
						{
							model.Level = "Register";
							var role = _customerService.GetCustomerRoleBySystemName(SystemCustomerRoleNames.Registered);
							if (null != role)
								model.LevelName = role.Name;
						}
						model.Gender = customer.GetAttribute<string>(SystemCustomerAttributeNames.Gender) == "M" ? 1 : 2;
						#region 绑定openId、formId
						if (!string.IsNullOrEmpty(openId))
						{
							_genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.OpenId, openId);
						}
						_customerService.UpdateCustomer(customer);
						model.OpenId = customer.GetAttribute<string>(SystemCustomerAttributeNames.OpenId);
						#endregion
						return Json(new { result = true, model });
					}
				case CustomerLoginResults.CustomerNotExist:
					msg = "用户不存在";
					break;
				case CustomerLoginResults.Deleted:
					msg = "用户已删除";
					break;
				case CustomerLoginResults.NotActive:
					msg = "用户未激活";
					break;
				case CustomerLoginResults.NotRegistered:
					msg = "用户未注册";
					break;
				case CustomerLoginResults.LockedOut:
					msg = "用户已冻结";
					break;
				case CustomerLoginResults.WrongPassword:
				default:
					msg = "密码错误";
					break;
			}
			return Json(new { result = false, msg });
		}

		/// <summary>
		/// 换取openid & session_key
		/// </summary>
		/// <param name="code"></param>
		/// <returns></returns>
		[HttpPost]
		public JsonResult OnLogin(string code)
		{
			string appId = "wx254193524213940e";
			string appSecret = "c020d4fcaceaef04d03194bcf408ba51";
			try
			{
				var jsonResult = SnsApi.JsCode2Json(appId: appId, secret: appSecret, jsCode: code);

				if (jsonResult.errcode == ReturnCode.请求成功)
				{
					//Session["WxOpenUser"] = jsonResult;//使用Session保存登陆信息（不推荐）
					//使用SessionContainer管理登录信息（推荐）
					var unionId = "";
					var sessionBag = SessionContainer.UpdateSession(null, jsonResult.openid, jsonResult.session_key, unionId);
					//返回openId、sessionId
					return Json(new { success = true, msg = "OK", sessionId = sessionBag.Key, openId = sessionBag.OpenId });
				}
				else
				{
					return Json(new { success = false, msg = jsonResult.errmsg });
				}
			}
			catch (Exception e)
			{
				return Json(new { success = false, msg = e.Message });
			}
		}

		#endregion

		#region CustomerRole

		/// <summary>
		/// 用户角色列表
		/// </summary>
		/// <param name="model"></param>
		/// <param name="guid"></param>
		/// <param name="sorter"></param>
		/// <returns></returns>
		[HttpPost]
		public JsonResult CustomerRoleList(CustomerRoleListModel model, string guid = "", string sorter = "")
		{
			if (!_permissionAntService.Authorize(guid, (int)PermissionAntEnum.customerrolelist))
				return Json(new { result = false, msg = "无权访问" });
			var roles = _customerService.GetAllCustomerRoles(name: model.Name, systemName: model.SystemName, showAll: !model.OnlyActive);
			var gridModel = new DataSourceResultAnt
			{
				list = roles.Select(PrepareCustomerRoleModelForList),
				pagination = null
			};
			return Json(new { result = true, gridModel });
		}

		/// <summary>
		/// 保存角色信息
		/// </summary>
		/// <param name="model"></param>
		/// <param name="guid"></param>
		/// <returns></returns>
		[HttpPost]
		public JsonResult SaveCustomerRole(CustomerRoleModel model, string guid)
		{
			if (!_permissionAntService.Authorize(guid, (int)PermissionAntEnum.customerrolelist))
				return Json(new { result = false, msg = "无权访问" });
			var customer = _customerService.GetCustomerByToken(guid);
			if (null != customer)
			{
				try
				{
					if (model.key == 0)
					{
						var role = new CustomerRole();
						role.Name = model.Name;
						role.SystemName = model.SystemName;
						role.Active = model.Active;
						role.IsSystemRole = false;
						_customerService.InsertCustomerRole(role);
						//activity log
						_customerActivityService.InsertActivity("AddNewCustomerRole", "新增角色 Id={0}", role.Id);
					}
					else
					{
						var role = _customerService.GetCustomerRoleById(model.key);
						if (null != role)
						{
							if (role.IsSystemRole && !model.Active)
								return Json(new { result = false, msg = "不能修改系统角色为禁用" });
							if (role.IsSystemRole && !role.SystemName.Equals(model.SystemName, StringComparison.InvariantCultureIgnoreCase))
								return Json(new { result = false, msg = "不能修改系统角色编码" });
							role.Name = model.Name;
							role.SystemName = model.SystemName;
							role.Active = model.Active;
							_customerService.UpdateCustomerRole(role);
							//activity log
							_customerActivityService.InsertActivity("EditCustomerRole", "修改角色 Id={0}", role.Id);
						}
					}
					return Json(new { result = true });
				}
				catch (Exception ex)
				{
					return Json(new { result = false, msg = ex.Message });
				}
			}
			else
				return Json(new { result = false, msg = "用户无效" });
		}

		/// <summary>
		/// 删除角色信息
		/// </summary>
		/// <param name="key"></param>
		/// <returns></returns>
		[HttpPost]
		public JsonResult DeleteCustomerRole(int[] key, string guid)
		{
			if (!_permissionAntService.Authorize(guid, (int)PermissionAntEnum.customerrolelist))
				return Json(new { result = false, msg = "无权访问" });
			try
			{
				var customer = _customerService.GetCustomerByToken(guid);
				if (null != customer)
				{
					foreach (var id in key)
					{
						var role = _customerService.GetCustomerRoleById(id);
						if (null != role)
						{
							if (role.IsSystemRole)
								return Json(new { result = false, msg = "不能删除系统角色" });
							_customerService.DeleteCustomerRole(role);
							//activity log
							_customerActivityService.InsertActivity("DeleteCustomerRole", "删除角色 Id={0}", role.Id);
						}
					}
				}
			}
			catch (Exception ex)
			{
				return Json(new { result = false, msg = ex.Message });
			}
			return Json(new { result = true });
		}
		#endregion

		#region Person

		/// <summary>
		/// 人员列表
		/// </summary>
		/// <param name="model"></param>
		/// <param name="guid"></param>
		/// <param name="currentPage"></param>
		/// <param name="pageSize"></param>
		/// <param name="sorter"></param>
		/// <returns></returns>
		[HttpPost]
		public JsonResult PersonList(PersonListModel model, string guid = "", int currentPage = 1, int pageSize = 10, string sorter = "")
		{
			if (!_permissionAntService.Authorize(guid, (int)PermissionAntEnum.persons))
				return Json(new { result = false, msg = "无权访问" });

			var persons = _personService.GetPersons(name: model.Name,
				departId: model.DepartmentId,
				gwxzId: model.GWXZ,
				natureId: model.Nature,
				pageIndex: currentPage - 1,
				pageSize: pageSize);
			var gridModel = new DataSourceResultAnt
			{
				list = persons.Select(PreparePersonModelForList),
				pagination = new PaginationModel
				{
					total = persons.TotalCount,
					pageSize = pageSize,
					current = currentPage
				}
			};
			return Json(gridModel);
		}

		/// <summary>
		/// 列表筛选条件
		/// </summary>
		/// <returns></returns>
		public JsonResult PersonListFilter()
		{
			var model = new PersonListModel();
			var departments = _departmentService.GetAllDepartments().Where(m => m.Active && !m.Deleted).ToList();
			foreach (var d in departments)
			{
				model.Departments.Add(new ItemModel { key = d.Id.ToString(), value = d.Name });
			}
			Type enumGWXZ = typeof(GWXZEnum);
			Enum.GetNames(enumGWXZ).ToList().ForEach(s =>
			{
				string value = Enum.Format(enumGWXZ, Enum.Parse(enumGWXZ, s), "d");
				model.GWXZs.Add(new ItemModel { key = value, value = s });
			});
			Type enumGender = typeof(GenderEnum);
			Enum.GetNames(enumGender).ToList().ForEach(s =>
			{
				string value = Enum.Format(enumGender, Enum.Parse(enumGender, s), "d");
				model.Genders.Add(new ItemModel { key = value, value = s });
			});
			Type enumNation = typeof(NationEnum);
			Enum.GetNames(enumNation).ToList().ForEach(s =>
			{
				string value = Enum.Format(enumNation, Enum.Parse(enumNation, s), "d");
				model.Nations.Add(new ItemModel { key = value, value = s });
			});
			Type enumPoliticsStatus = typeof(PoliticsStatusEnum);
			Enum.GetNames(enumPoliticsStatus).ToList().ForEach(s =>
			{
				string value = Enum.Format(enumPoliticsStatus, Enum.Parse(enumPoliticsStatus, s), "d");
				model.PoliticsStatuss.Add(new ItemModel { key = value, value = s });
			});
			Type enumStatus = typeof(WorkStatusEnum);
			Enum.GetNames(enumStatus).ToList().ForEach(s =>
			{
				string value = Enum.Format(enumStatus, Enum.Parse(enumStatus, s), "d");
				model.Statuss.Add(new ItemModel { key = value, value = s });
			});
			Type enumNature = typeof(NatureEnum);
			Enum.GetNames(enumNature).ToList().ForEach(s =>
			{
				string value = Enum.Format(enumNature, Enum.Parse(enumNature, s), "d");
				model.Natures.Add(new ItemModel { key = value, value = s });
			});
			Type enumEducation = typeof(EducationEnum);
			Enum.GetNames(enumEducation).ToList().ForEach(s =>
			{
				string value = Enum.Format(enumEducation, Enum.Parse(enumEducation, s), "d");
				model.Educations.Add(new ItemModel { key = value, value = s });
			});
			Type enumZCLevel = typeof(ZCLevelEnum);
			Enum.GetNames(enumZCLevel).ToList().ForEach(s =>
			{
				string value = Enum.Format(enumZCLevel, Enum.Parse(enumZCLevel, s), "d");
				model.ZCLevels.Add(new ItemModel { key = value, value = s });
			});
			Type enumJNLevel = typeof(JNLevelEnum);
			Enum.GetNames(enumJNLevel).ToList().ForEach(s =>
			{
				string value = Enum.Format(enumJNLevel, Enum.Parse(enumJNLevel, s), "d");
				model.JNLevels.Add(new ItemModel { key = value, value = s });
			});
			return Json(model, JsonRequestBehavior.AllowGet);
		}

		/// <summary>
		/// 保存人员信息
		/// </summary>
		/// <param name="model"></param>
		/// <param name="guid"></param>
		/// <returns></returns>
		[HttpPost]
		public JsonResult SavePerson(PersonModel model, string guid)
		{
			if (!_permissionAntService.Authorize(guid, (int)PermissionAntEnum.persons))
				return Json(new { result = false, msg = "无权访问" });
			try
			{
				var customer = _customerService.GetCustomerByToken(guid);
				if (null != customer)
				{
					if (model.key == 0)
					{
						var person = new Person
						{
							Name = model.Name,
							DepartmentId = model.DepartmentId,
							BMNSJG = model.BMNSJG,
							GWMC = model.GWMC,
							GWXZ = model.GWXZ,
							TelPhone = model.TelPhone,
							GenderId = model.GenderId,
							SFZH = model.SFZH,
							BirthOn = model.BirthOn,
							WorkOn = model.WorkOn,
							NationId = model.NationId,
							Birthplace = model.Birthplace,
							PoliticsStatus = model.PoliticsStatus,
							JoinOn = model.JoinOn,
							Status = model.Status,
							Nature = model.Nature,
							Education = model.Education,
							School = model.School,
							Degree = model.Degree,
							ZC = model.ZC,
							ZCLevel = model.ZCLevel,
							JN = model.JN,
							JNLevel = model.JNLevel
						};
						_personService.InsertPerson(person);
						//activity log
						_customerActivityService.InsertActivity("AddNewPerson", "新增人员 Id={0}", person.Id);
					}
					else
					{
						var person = _personService.GetPersonById(model.key);
						if (null != person)
						{
							person.Name = model.Name;
							person.DepartmentId = model.DepartmentId;
							person.BMNSJG = model.BMNSJG;
							person.GWMC = model.GWMC;
							person.GWXZ = model.GWXZ;
							person.TelPhone = model.TelPhone;
							person.GenderId = model.GenderId;
							person.SFZH = model.SFZH;
							person.BirthOn = model.BirthOn;
							person.WorkOn = model.WorkOn;
							person.NationId = model.NationId;
							person.Birthplace = model.Birthplace;
							person.PoliticsStatus = model.PoliticsStatus;
							person.JoinOn = model.JoinOn;
							person.Status = model.Status;
							person.Nature = model.Nature;
							person.Education = model.Education;
							person.School = model.School;
							person.Degree = model.Degree;
							person.ZC = model.ZC;
							person.ZCLevel = model.ZCLevel;
							person.JN = model.JN;
							person.JNLevel = model.JNLevel;
							_personService.UpdatePerson(person);
							//activity log
							_customerActivityService.InsertActivity("EditPerson", "修改人员 Id={0}", person.Id);
						}
					}
					return Json(new { result = true });
				}
				else
					return Json(new { result = false, msg = "用户无效" });
			}
			catch (Exception ex)
			{
				return Json(new { result = false, msg = ex.Message });
			}
		}

		/// <summary>
		/// 删除人员
		/// </summary>
		/// <param name="key"></param>
		/// <param name="guid"></param>
		/// <returns></returns>
		[HttpPost]
		public JsonResult DeletePerson(int[] key, string guid)
		{
			if (!_permissionAntService.Authorize(guid, (int)PermissionAntEnum.persons))
				return Json(new { result = false, msg = "无权访问" });
			try
			{
				var customer = _customerService.GetCustomerByToken(guid);
				if (null != customer)
				{
					foreach (var id in key)
					{
						var person = _personService.GetPersonById(id);
						if (null != person && !person.Deleted)
						{
							person.Deleted = true;
							_personService.UpdatePerson(person);
						}
					}
				}
			}
			catch (Exception ex)
			{
				return Json(new { result = false, msg = ex.Message });
			}
			return Json(new { result = true });
		}
		#endregion

		#region Export / Import
		[HttpPost]
		public JsonResult PersonExport(bool isAll = false, int[] key = null)
		{
			var persons = new List<Person>();
			try
			{
				if (isAll)
					persons = _personService.GetPersons().ToList();
				else if (key != null)
					persons = _personService.GetPersonsByIds(key).ToList();

				return Json(new { result = true, data = persons.Select(PreparePersonExportModelForList) });
			}
			catch (Exception ex)
			{
				return Json(new { result = false, msg = ex.Message });
			}
		}
		#endregion
	}
}
